# api/v1/translate.py
from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from pydantic import BaseModel
from typing import Optional
from core.translation_engine import translation_engine
import logging

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/translate", tags=["Translation"])

# ========================================================
# 文本翻译接口
# ========================================================

class TranslateTextRequest(BaseModel):
    text: str
    source_lang: str = "auto"
    target_lang: str = "en"

@router.post("/text")
async def translate_text(request: TranslateTextRequest):
    """
    文本翻译接口
    
    按照 8.3.2 MT模型接口规范实现
    """
    try:
        logger.info(f"开始文本翻译: {request.text[:50]}... | 源={request.source_lang}, 目标={request.target_lang}")
        
        result = translation_engine.translate_text(
            text=request.text,
            source_lang=request.source_lang,
            target_lang=request.target_lang
        )
        
        # 按照接口规范返回结果
        return {
            "translatedText": result["translated_text"],
            "confidence": result["confidence"],
            "sourceLang": result["source_lang"],
            "targetLang": result["target_lang"],
            "engine": result["engine"],
            "timestamp": result["timestamp"]
        }
        
    except Exception as e:
        logger.error(f"文本翻译失败: {e}")
        raise HTTPException(status_code=500, detail=f"翻译失败: {str(e)}")

# ========================================================
# 音频翻译接口
# ========================================================

class TranslateAudioRequest(BaseModel):
    source_lang: str = "auto"
    target_lang: str = "en"
    enable_translation: bool = True
    return_segments: bool = False

@router.post("/audio")
async def translate_audio(
    audio_file: UploadFile = File(...),
    source_lang: str = Form("auto"),
    target_lang: str = Form("en"),
    enable_translation: bool = Form(True),
    return_segments: bool = Form(False)
):
    """
    音频翻译接口
    
    按照 8.3.1 ASR模型接口规范实现
    """
    try:
        # 验证文件类型
        if not audio_file.content_type or not audio_file.content_type.startswith('audio/'):
            raise HTTPException(status_code=400, detail="只支持音频文件")
        
        logger.info(f"开始音频翻译: {audio_file.filename} | 源={source_lang}, 目标={target_lang}")
        
        # 保存临时文件
        import tempfile
        import os
        
        with tempfile.NamedTemporaryFile(delete=False, suffix=f".{audio_file.filename.split('.')[-1]}") as temp_file:
            content = await audio_file.read()
            temp_file.write(content)
            temp_file_path = temp_file.name
        
        try:
            # 调用翻译引擎
            result = translation_engine.translate_audio(
                audio_path=temp_file_path,
                source_lang=source_lang,
                target_lang=target_lang,
                enable_translation=enable_translation,
                return_segments=return_segments
            )
            
            # 按照接口规范返回结果
            response = {
                "text": result["source_text"],  # ASR 转录文本
                "translatedText": result["translated_text"],  # 翻译文本
                "confidence": result["confidence"],
                "sourceLang": result["source_lang"],
                "targetLang": result["target_lang"],
                "duration": result.get("duration", 0),
                "engine": result["engine"],
                "timestamp": result["timestamp"]
            }
            
            # 添加分段信息（如果请求）
            if return_segments and "segments" in result:
                response["segments"] = result["segments"]
            
            logger.info(f"音频翻译完成: {result['source_text'][:50]}...")
            return response
            
        finally:
            # 清理临时文件
            if os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
                
    except Exception as e:
        logger.error(f"音频翻译失败: {e}")
        raise HTTPException(status_code=500, detail=f"音频翻译失败: {str(e)}")

# ========================================================
# 文件翻译接口
# ========================================================

@router.post("/file")
async def translate_file(
    file: UploadFile = File(...),
    source_lang: str = Form("auto"),
    target_lang: str = Form("en")
):
    """
    文件翻译接口 - 支持音频文件翻译
    """
    try:
        logger.info(f"开始文件翻译: {file.filename} | 源={source_lang}, 目标={target_lang}")
        
        # 检查文件类型
        if not file.content_type:
            raise HTTPException(status_code=400, detail="无法识别文件类型")
        
        # 目前只支持音频文件翻译
        if file.content_type.startswith('audio/'):
            # 复用音频翻译逻辑
            return await translate_audio(
                audio_file=file,
                source_lang=source_lang,
                target_lang=target_lang,
                enable_translation=True,
                return_segments=False
            )
        else:
            raise HTTPException(
                status_code=400, 
                detail=f"暂不支持的文件类型: {file.content_type}，目前只支持音频文件"
            )
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"文件翻译失败: {e}")
        raise HTTPException(status_code=500, detail=f"文件翻译失败: {str(e)}")

# ========================================================
# 批量翻译接口
# ========================================================

class BatchTranslateRequest(BaseModel):
    texts: list[str]
    source_lang: str = "auto"
    target_lang: str = "en"

@router.post("/batch")
async def batch_translate_text(request: BatchTranslateRequest):
    """批量文本翻译"""
    try:
        logger.info(f"开始批量翻译: {len(request.texts)} 个文本 | 源={request.source_lang}, 目标={request.target_lang}")
        
        results = translation_engine.batch_translate_text(
            texts=request.texts,
            source_lang=request.source_lang,
            target_lang=request.target_lang
        )
        
        return {
            "results": results,
            "total": len(results),
            "success_count": len([r for r in results if r["confidence"] > 0])
        }
        
    except Exception as e:
        logger.error(f"批量翻译失败: {e}")
        raise HTTPException(status_code=500, detail=f"批量翻译失败: {str(e)}")

# ========================================================
# 兼容性接口（向后兼容）
# ========================================================

class TranslateRequest(BaseModel):
    text: str
    target_lang: str

@router.post("/legacy")
async def translate_text_legacy(request: TranslateRequest):
    """
    兼容性接口：保持向后兼容
    
    已弃用：建议使用 /text 端点
    """
    try:
        logger.warning("使用已弃用的兼容性接口，建议迁移到 /text 端点")
        
        result = translation_engine.translate_text(
            text=request.text,
            source_lang="auto",
            target_lang=request.target_lang
        )
        
        return {
            "original_text": request.text,
            "translated_text": result["translated_text"]
        }
        
    except Exception as e:
        logger.error(f"兼容性翻译失败: {e}")
        raise HTTPException(status_code=500, detail=f"翻译失败: {str(e)}")

# ========================================================
# 语言支持查询接口
# ========================================================

@router.get("/languages")
async def get_supported_languages():
    """获取支持的语言列表"""
    try:
        languages = translation_engine.get_supported_languages()
        return languages
    except Exception as e:
        logger.error(f"获取语言列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取语言列表失败: {str(e)}")